from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from Home.models import Department, Doctor
from random import randint, uniform, choice


DEPARTMENTS = [
    ("内科", "涵盖心血管、呼吸、消化、内分泌等常见疾病诊疗"),
    ("外科", "普外科、胸外科、神经外科等外科手术治疗"),
    ("儿科", "儿童内外科常见病及保健"),
    ("妇产科", "妇科与产科相关诊疗"),
    ("骨科", "四肢、脊柱、关节等损伤与疾病治疗"),
    ("眼科", "眼部疾病与视光学"),
    ("口腔科", "口腔种植、正畸、修复与保健"),
    ("皮肤科", "皮肤与性病诊疗"),
    ("中医科", "中医内科、针灸推拿与中药治疗"),
    ("急诊科", "急危重症救治"),
]


TITLES = ["resident", "attending", "associate", "chief"]


SPECIALTIES = {
    "内科": ["高血压", "糖尿病", "冠心病", "甲状腺疾病"],
    "外科": ["胆囊结石", "疝气", "阑尾炎", "甲状腺结节"],
    "儿科": ["发热咳嗽", "生长发育", "过敏", "腹泻"],
    "妇产科": ["产检", "不孕不育", "子宫肌瘤", "卵巢囊肿"],
    "骨科": ["关节炎", "运动损伤", "骨折", "颈椎病"],
    "眼科": ["近视", "白内障", "青光眼", "干眼症"],
    "口腔科": ["种植牙", "正畸", "龋齿", "牙周病"],
    "皮肤科": ["痤疮", "湿疹", "银屑病", "脱发"],
    "中医科": ["针灸", "内科调理", "风湿", "失眠"],
    "急诊科": ["创伤", "中毒", "心梗卒中", "多发伤"],
}


def random_avatar(name: str):
    return f"https://api.dicebear.com/7.x/initials/svg?seed={name}"


class Command(BaseCommand):
    help = "Seed departments and doctors with demo data"

    def add_arguments(self, parser):
        parser.add_argument("--per", type=int, default=5, help="Ensure at least N doctors per department (min 5)")
        parser.add_argument("--add", type=int, default=0, help="Append N doctors to each department regardless of existing")
        parser.add_argument("--dept", nargs='*', default=None, help="Only seed specified departments (names, space separated)")

    def handle(self, *args, **options):
        per = max(5, int(options.get("per") or 5))
        add = int(options.get("add") or 0)
        only = options.get("dept") or None

        self.stdout.write(self.style.NOTICE(f"Creating departments..."))
        name_to_dept = {}
        for idx, (name, desc) in enumerate(DEPARTMENTS):
            dept, _ = Department.objects.get_or_create(
                name=name,
                defaults={
                    "description": desc,
                    "icon": "🏥",
                    "sort_order": idx,
                    "is_active": True,
                },
            )
            name_to_dept[name] = dept

        self.stdout.write(self.style.NOTICE(f"Creating doctors (>= {per} per department)..."))
        total = 0
        target_departments = [d for d in DEPARTMENTS if (only is None or d[0] in set(only))]

        for name, _ in target_departments:
            dept = name_to_dept[name]
            existing = Doctor.objects.filter(department=dept).count()
            need = add if add > 0 else max(0, per - existing)
            for i in range(need):
                serial = existing + i + 1
                doc_name = f"{name}医生{serial}"
                Doctor.objects.create(
                    name=doc_name,
                    title=choice(TITLES),
                    department=dept,
                    avatar=random_avatar(doc_name),
                    introduction=f"{doc_name}，从医{randint(5, 30)}年，擅长{choice(SPECIALTIES.get(name, ['常见病']))}",
                    specialties=SPECIALTIES.get(name, ["常见病", "多发病"]),
                    experience_years=randint(3, 35),
                    education=choice(["本科", "硕士", "博士"]),
                    hospital="京东医疗示例医院",
                    consultation_fee=round(uniform(20, 200), 2),
                    rating=round(uniform(3.5, 5.0), 1),
                    rating_count=randint(5, 500),
                    status="active",
                    is_featured=choice([True, False, False]),
                )
                total += 1

        self.stdout.write(self.style.SUCCESS(f"Done. Added {total} doctors across {len(target_departments)} departments."))


